<?php require_once '../yubiphpbase/appinclude.php';
require_once '../yubiphpbase/yubi_lib.php';

$otp = strtolower(getHttpVal('otp', ''));

if (strlen($otp) < 10 || strlen(($err = verifyYubikeyOtp($otp))) > 0) {
	if (strlen($otp) < 10) {
		$err = 'Invalid OTP';
	}
	$_SESSION['alert'] = CLICK2LOGIN . '<p>'.$err;
	writeLog('OTP failed: '.$err.', otp='.$otp);
	header('Location: index.php');
	exit;
}

$devId = substr($otp, 0, DEVICE_ID_LEN);

$a = getKeyInfo($devId);

if ($a['perm'] > 2) {
	$_SESSION['alert'] = 'This Yubikey does not have admin rights to log on to the management console.';
	header('Location: index.php');
	exit;
} else if (($usrid = $a['usrid']) > 0) { // Key exists
	letUserIn($usrid, $a, $devId);	
	$_SESSION['email'] = $a['email'];
	$pin = $a['pin'];
	if (strlen($pin) >= PW_MIN) {
		header('Location: yubi_askpin.php?devid='.$devId);
		$_SESSION['usrid'] = 0;
		exit;
	}	
	addHist($usrid, 'Yubikey '.$devId . 'login');
	header('Location: index.php');
	exit;
} else { // New key
	$_SESSION['alert'] = 'Your Yubikey is not an admin key of any client.';
	header('Location: index.php');
	exit;
}

function letUserIn($usrid, $a, $devId) {
	global $SESS_SALT, $readOnly;
	
	$note = $a['note'];
	
	setcookie('usrid', aesEncrypt($usrid), time() + A_MONTH_IN_SECS);
	
	$_SESSION['usrid'] = $usrid;
	$_SESSION['keyid'] = $a['keyid'];
	$_SESSION['client'] = $a['client'];
	$_SESSION['timeout'] = DEF_TIMEOUT_IN_SECS;
	$_SESSION['last'] = time();
	$_SESSION['email'] = $a['email'];
	$_SESSION['chk_time'] = $a['chk_time'];
	writeLog('Check time? '.$a['chk_time']);
  	$_SESSION['hi'] = '<div class="welcomeback welcomeout_txt">Hi, '.$a['email'].
  		makePopupURL('edit_prefs.php', ' <font size=-1 color=#EEEEEE> ( Edit ) </font>', 400).  	
  		', admin of '.
                makePopupURL('edit_client.php?client='.$a['client'],
		  '(Client-'.$a['client'],500,'#EEEEEE','Edit the Client').
  		'), yubikey id: '. $devId;

  	$_SESSION['hi'] .= '</div>'.
	  '<div class="login_nav logout_txt">'.
	  '<a href=logoff.php>Log Out</a></div>';

	setAcctLastAccessByID($a['usrid']);	
}
?>
